package linhnv.app;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
//import android.widget.VideoView;
import android.widget.Toast;

public class AudioStreaming extends TabActivity implements OnTabChangeListener{
    /** Called when the activity is first created. */
//	 private String path ="rtsp://14.0.19.168/wildlife.mp4"; 
//	//private String path="http://daily3gp.com/vids/familyguy_has_own_orbit.3gp";
//	 private VideoView mVideoView;
	TabHost.TabSpec tabHome;
	TabHost.TabSpec tabHot;
	TabHost.TabSpec tabSettings;
	TabHost tabHost;
	Handler h;
	private ProgressDialog m_ProgressDialog = null;
	private Runnable viewOrders;
	private static boolean nw= false;
	private static Home homeSelf;
	public static FrameLayout frameTitleLayout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
      //Remove title bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//Remove notification bar
		//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.main);
		
        h = new Handler() {

            @Override
            public void handleMessage(Message msg) {
            	m_ProgressDialog.dismiss();
                if (msg.what != 1) { // code if not connected
                	Log.w("Linhnv","================network is ok");
                	
                	m_ProgressDialog.dismiss();
                	nw=true;
                	setLayout();
                } else { // code if connected
                	Log.w("Linhnv","================network is not ok");
                	m_ProgressDialog.dismiss();
                	Toast toast = Toast.makeText(AudioStreaming.this, "Please check your wifi network again!", 15000);
                	toast.show();
                	nw=false;
                	//setContentView(R.layout.setting);
                }

            }
        };
       
        viewOrders = new Runnable() {
			@Override
			public void run() {
				//getOrders();
				 isNetworkAvailable(h,500);
				 try {
					Thread.sleep(6000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		Thread thread = new Thread(null, viewOrders, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(AudioStreaming.this,
				"Please wait...", "Retrieving data ...", true);
			
			
        
	    
    }
    private void setLayout()
    {
    	if(nw){
			//setContentView(R.layout.main);
        	Log.w("Linhnv","================network is ok come here: "+nw);
        	
        	checkListApplication();
            if( isAppInstalled("com.daroonsoft.player"))
            {
            	Log.w("Linhnv","============daroon player has been installed");
            }else
            {
            	showDialog();
            }
            Resources res = getResources(); // Resource object to get Drawables
    	    tabHost = getTabHost();  // The activity TabHost
    	    Intent intent;  // Reusable Intent for each tab

    	    // Create an Intent to launch an Activity for the tab (to be reused)
    	    intent = new Intent().setClass(this, Home.class);
    	    // Initialize a TabSpec for each tab and add it to the TabHost
    	    tabHome = tabHost.newTabSpec("home").setIndicator("Home",
                    res.getDrawable(R.drawable.home_tab))
                    .setContent(intent);
    	    tabHost.addTab(tabHome);
    	    // Do the same for the other tabs
    	    intent = new Intent().setClass(this, HotTab.class);
    	    intent.putExtra("type", 0);
    	    tabHot = tabHost.newTabSpec("hot").setIndicator("Hot",
    	    		 res.getDrawable(R.drawable.tab_hot))
    	                  .setContent(intent);
    	    tabHost.addTab(tabHot);

    	    intent = new Intent().setClass(this, Setting.class);
    	    tabSettings = tabHost.newTabSpec("setting").setIndicator("Setting",
    	                      res.getDrawable(R.drawable.tab))
    	                  .setContent(intent);
    	    tabHost.addTab(tabSettings);
    	    tabHost.setCurrentTab(0);
            
    	    tabHost.setOnTabChangedListener(this);
    	    
//    	    tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.home_tab_bg);
//    	    tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.hot_tab_bg);
//    	    tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.setting_tab_bg);
//    	    tabHost.getTabWidget().setStripEnabled(false);
    	    frameTitleLayout = (FrameLayout)findViewById(R.id.mainTitleBar);
			}else{
				//setContentView(R.layout.setting);
			}
    }
    public static void setHomeSelf(Home home)
    {
    	homeSelf = home;
    }
    public static Home getHomeSelf()
    {
    	return homeSelf;
    }
    @Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		if(tabId.equals("home"))
		{
			homeSelf.reset();
		}
		else if(tabId.equals("hot"))
		{
			frameTitleLayout.getLayoutParams().height = 0;
		}
		else
		{
			frameTitleLayout.getLayoutParams().height = (int) (getResources().getDisplayMetrics().density * 40);
		}
	}
	private void showDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Please install Daroon Player for your best enjoy !")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               /*
		                * go to download and install Daroon player function
		                */
//		        	   Intent goToMarket = new Intent(Intent.ACTION_VIEW)
//		        	    .setData(Uri.parse("http://market.android.com/details?id=com.daroonsoft.player"))
//		        	    .setType("application/vnd.android.package-archive");
//		        	    
//		        	startActivity(goToMarket);
		        	  Update("http://daroon-player.googlecode.com/svn/trunk/dsplayer.apk");
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	private void checkListApplication()
	{
		List pkgAppsList = this.getPackageManager().getInstalledPackages(0);
		for(int i =0 ; i < pkgAppsList.size();i++)
		{
			Log.w("Linhnv","============application"+pkgAppsList.get(i).toString());
		}
	}
	
	private boolean isAppInstalled(String uri) {
		PackageManager pm = getPackageManager();
		boolean installed = false;
		try {
		pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
		installed = true;
		} catch (PackageManager.NameNotFoundException e) {
		installed = false;
		}
		return installed;
		}
	public  void isNetworkAvailable(final Handler handler, final int timeout) {

        // ask fo message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)

			try {
				Thread.sleep(5000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		new Thread() {

            private boolean responded = false;

            @Override
            public void run() {

                // set 'responded' to TRUE if is able to connect with google mobile (responds fast)
            	
                new Thread() {

                    @Override
                    public void run() {
                        HttpGet requestForTest = new HttpGet("http://google.com");
                        try {
                            new DefaultHttpClient().execute(requestForTest); // can last...
                            responded = true;
                            sleep(3000);
                        } catch (Exception e) {}
                    }

                }.start();

                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) { 
                            waited += 100;
                        }
                    }
                } 
                catch(InterruptedException e) {} // do nothing 
                finally { 
                    if (!responded) { handler.sendEmptyMessage(0); } 
                    else { handler.sendEmptyMessage(1); }
                }

            }

        }.start();

}
	public void Update(String apkurl){
	      try {
	            URL url = new URL(apkurl);
	            HttpURLConnection c = (HttpURLConnection) url.openConnection();
	            
	            c.setRequestMethod("GET");
	            c.setDoOutput(true);
	            c.connect();
	           
	            String PATH = Environment.getExternalStorageDirectory() + "/download/";
	            
	            File file = new File(PATH);
	            file.mkdirs();
	            File outputFile = new File(file, "app.apk".toString());
	            
	            FileOutputStream fos = new FileOutputStream(outputFile);
	            
	            InputStream is = c.getInputStream();
	            
	            byte[] buffer = new byte[1024];
	            int len1 = 0;
	            while ((len1 = is.read(buffer)) != -1) {
	                fos.write(buffer, 0, len1);
	            }
	            
	            fos.close();
	            is.close();//till here, it works fine - .apk is download to my sdcard in download file
	            
	            Intent intent = new Intent(Intent.ACTION_VIEW);
	            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
	            startActivity(intent);  

	        } catch (IOException e) {
	            Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
	        }
	  }  
	
}